<template>
    <div class="balance_detail">
        <!-- 导航栏 -->
        <van-nav-bar 
            title="红包" 
            left-arrow 
            fixed 
            @click-left="onClickLeft"
            :class="{ scrolled: isScrolled }" />
        
        <!-- 顶部金额展示区域 -->
        <div class="balance_detail_top">
            <div class="red_top">
                <div>{{ RedEnvelopeInfo.open_amount?.toFixed(2) || 0 }}</div>
                <div>今日获得红包金额</div>
            </div>
            <!-- 红包图标 - 根据状态显示不同图片 -->
            <img v-if="RedEnvelopeInfo.open_status == 1" 
                 src="../../images/mine/red_icon.png" 
                 alt="" 
                 @click="openRed">
            <img v-else src="../../images/mine/red_icon3.png" alt="">
        </div>
        
        <!-- 主要内容区域 -->
        <div class="balance_detail_content">
            <!-- 日期筛选 -->
            <div class="balance_detail_content_day" @click="dayShow = true">
                {{ days }}<van-icon name="arrow-down" style="color: #999;" />
            </div>
            
            <!-- 红包列表 -->
            <van-list style="height: 100%;" 
                     v-model="loading" 
                     :finished="finished" 
                     finished-text="没有更多了" 
                     @load="onLoad">
                <div class="balance_list" v-for="(item, index) in fansList" :key="index">
                    <div class="balance_list_left">
                        <div>{{ item.node }}</div>
                        <div>{{ item.create_time }}</div>
                    </div>
                    <div class="balance_list_right">+{{ item.amount?.toFixed(2) || 0 }}</div>
                </div>
            </van-list>
        </div>
        
        <!-- 日期选择弹窗 -->
        <van-popup v-model="dayShow" position="bottom" :style="{ height: '40%' }">
            <van-datetime-picker 
                :value="new Date(currentDate)" 
                type="date" 
                title="选择年月日" 
                :min-date="minDate"
                :max-date="maxDate" 
                @confirm="onConfirmDay" 
                @cancel="onCancelDay" />
        </van-popup>
        
        <!-- 遮罩层 -->
        <van-overlay :show="redShow" />
        
        <!-- 可领取红包弹窗 -->
        <div class="red_box" v-if="isshow">
            <div class="red_box_content">
                <div class="red_title">
                    <div>你有红包待查收</div>
                </div>
                <!-- 红包图标 - 点击打开 -->
                <img v-if="isShowAmt" 
                     src="../../images/mine/red_icon_01.png" 
                     alt="" 
                     @click="openRedEnvelope">
                <img v-else :src="`${rxImg + '?tempid=' + Math.random()}`" alt="">
            </div>
            <img src="../../images/mine/clone.png" alt="" @click="closeOverlay">
        </div>
        
        <!-- 红包打开动画效果 -->
        <div class="red_box2" v-if="isHidden">
            <img class="dynamic-image image1" 
                 src="../../images/mine/red_bg2.png" 
                 alt="背景图1"
                 :class="{ fadeOut: isFadingOut }" />
            <img class="dynamic-image image2" 
                 src="../../images/mine/red_bg1.png" 
                 alt="背景图2"
                 :class="{ fadeOut: isFadingOut }" />
        </div>
        
        <!-- 暂无红包弹窗 -->
        <div class="red_box" v-if="isshowOpen">
            <div class="red_box_content">
                <div class="red_title">
                    <div>{{ redInfo.title || '当前无可领取红包' }}</div>
                    <!-- <div class="tips">{{ redInfo.tip_msg }}</div> -->
                </div>
            </div>
            <img src="../../images/mine/clone.png" alt="" @click="closeOverlay">
        </div>
    </div>
</template>
<script>
import { parseTime } from '@/tool/methods'
import { 
    CAPITAL_PACKET_INFO, 
    CAPITAL_PACKET_OPEN, 
    CAPITAL_PACKET_OPEN_LIST, 
} from '@/api/mine'

export default {
    name: 'balance',
    data() {
        return {
            days: "本月", // 日期筛选显示文本
            dayShow: false, // 日期选择器显示状态
            minDate: new Date(1930, 0, 1), // 日期选择器最小日期
            maxDate: new Date(2999, 10, 1), // 日期选择器最大日期
            currentDate: new Date(), // 当前选中日期
            loading: false, // 列表加载状态
            finished: false, // 列表加载完成状态
            notifyList: [], // 通知列表（未使用）
            redShow: false, // 遮罩层显示状态
            isshow: null, // 可领取红包弹窗显示状态
            isshowOpen: null, // 暂无红包弹窗显示状态
            rxImg: require('../../images/mine/amt_icon.gif'), // 红包动画图片
            timer: null, // 定时器
            setImage: null, // 图片设置（未使用）
            isShowAmt: true, // 是否显示红包打开按钮
            isFadingOut: false, // 动画消失状态
            isHidden: false, // 动画容器显示状态
            isScrolled: false, // 导航栏滚动状态
            RedEnvelopeInfo: {}, // 红包信息
            fansList: [], // 红包列表数据
            page: 1, // 当前页码
            year: '', // 筛选年份
            month: '', // 筛选月份
            day: '', // 筛选日期
            type: null, // 红包类型
            pageSize: 20, // 每页数量
            date_range: 0, // 日期范围（未使用）
            redInfo: {}, // 红包详情信息
        }
    },
    
    created() {
        // 初始化页面数据
        localStorage.removeItem("redList")
        
        this.$http.get(CAPITAL_PACKET_INFO).then(res => {
            // console.log(res.data, '红包信息')
            this.RedEnvelopeInfo = res.data
            this.checkTime() // 检查红包状态
        })
    },
    
    beforeDestroy() {
        window.removeEventListener("scroll", this.handleScroll);
    },
    
    mounted() {
        window.addEventListener("scroll", this.handleScroll);
    },
    
    destroyed() {
        clearInterval(this.timer) // 清理定时器
    },
    
    methods: {
        // 处理页面滚动
        handleScroll() {
            this.isScrolled = window.scrollY > 26;
        },
        
        // 图片预加载
        loadImg(url, callback) {
            var img = new Image();
            img.src = url;
            img.onload = function() {
                callback(img);
            };
        },
        
        // 设置图片（未完整实现）
        setImg(img) {
            this.rxImg = "url(" + img.src + ")" + "no-repeat  center -50px/ 92% #152348"
        },
        
        // 打开红包
        openRedEnvelope() {
            this.isShowAmt = false
            // 设置红包动画
            this.timer = setInterval(() => {
                this.rxImg = require('../../images/mine/amt_icon.gif') + '?' + Math.random()
                this.loadImage(this.bgGif, this.setImage)
            }, 700)
            
            this.$http.post(CAPITAL_PACKET_OPEN).then(res => {
                console.log(res.data, '打开红包')
                clearInterval(this.timer)
                setTimeout(() => {
                    this.isshow = false
                    this.isHidden = true;
                    setTimeout(() => {
                        this.startAnimation(res.data) // 开始打开动画
                    }, 50)
                }, 1000)
            }).catch(() => {
                this.isShowAmt = true
                clearInterval(this.timer)
            })
        },
        
        // 开始红包打开动画
        startAnimation(data) {
            this.isFadingOut = true;
            setTimeout(() => {
                this.isFadingOut = false;
                this.isHidden = false;
                this.redShow = false;

                this.$nextTick(() => {
                    if (data.status == 1) {
                        // 打开成功，跳转到详情页
                        localStorage.setItem("redList", JSON.stringify(data));
                        this.$router.push({ path: '/redEnvelopeDetail' });
                    } else {
                        // 打开失败，显示提示信息
                        this.redShow = true;
                        this.isshowOpen = true;
                        this.isShowAmt = true
                        this.redInfo = data;
                    }
                });
            }, 500);
        },
        
        // 检查红包状态
        checkTime() {
            if (this.RedEnvelopeInfo.open_status == 1) {
                this.isshow = true;
                this.redShow = true
                this.isshowOpen = false
            } 
            // else if (this.RedEnvelopeInfo.open_status === 0) {
            //     // 当open_status为0时，显示无可领取红包弹窗
            //     this.redShow = true;
            //     this.isshow = false;
            //     this.isshowOpen = true
            // } 
            else {
                this.redShow = false
            }
        },
        
        // 关闭遮罩层和弹窗
        closeOverlay() {
            this.redShow = false;
            this.isshow = false;
            this.isshowOpen = false
            clearInterval(this.timer)
        },
        
        // 打开红包弹窗
        openRed() {
            this.redShow = true;
            this.checkTime()
        },
        
        // 返回上一页
        onClickLeft() {
            this.$router.back()
        },
        
        // 日期选择确认
        onConfirmDay(val) {
            this.currentDate = parseTime(val, '{y}-{m}-{d}')
            this.days = this.currentDate
            this.year = this.currentDate.split('-')[0]
            this.month = this.currentDate.split('-')[1]
            this.day = this.currentDate.split('-')[2]
            this.dayShow = false
            this.page = 1
            this.fansList = []
            this.finished = false
            this.loading = true // 设置loading状态，避免van-list自动触发load事件
            this.$nextTick(() => {
                this.onLoad() // 在nextTick中调用onLoad
            })
        },
        
        // 日期选择取消
        onCancelDay() {
            this.dayShow = false
            this.days = '本月'
            this.year = ''
            this.month = ''
            this.day = ''
            this.page = 1
            this.finished = false
            this.fansList = []
            this.loading = true // 设置loading状态，避免van-list自动触发load事件
            this.$nextTick(() => {
                this.onLoad() // 在nextTick中调用onLoad
            })
        },
        
        // 加载红包列表
        onLoad() {
            let params = {};
            params["page_num"] = this.page;
            params["page_size"] = this.pageSize;
            params['year'] = this.year;
            params['month'] = this.month;
            params['day'] = this.day;
            params['type'] = this.$route.query.id == 1 ? 0 : 1
            
            this.$http.get(CAPITAL_PACKET_OPEN_LIST, {
                params: params
            }).then((res) => {
                const { list } = res.data;
                this.total_count = res.data.pages.total_count;
                
                if (list && list.length) {
                    this.page++;
                    this.fansList = this.fansList.concat(list);
                    this.loading = false;
                    
                    if (list.length < this.pageSize) {
                        this.finished = true;
                    }
                } else {
                    this.finished = true;
                }
            });
        }
    }
}
</script>
<style lang="scss" scoped>
.balance_detail {
    padding-top: 46px;
    background-color: #F2F4F5;
    height: calc(100vh - 46px);
    position: relative;

    ::v-deep .van-hairline--bottom::after {
        border: none;
    }

    ::v-deep .van-icon {
        color: #fff;
    }

    ::v-deep .van-nav-bar__title {
        width: 150px;
        color: #fff;
    }

    ::v-deep .van-nav-bar__arrow {
        font-size: 20px;
    }

    ::v-deep .van-nav-bar__text {
        color: #fff;
    }

    ::v-deep .van-nav-bar {
        background: transparent;
        position: fixed; // 改为固定定位
        top: 0; // 添加这行
        left: 0; // 添加这行
        right: 0; // 添加这行
        z-index: 1; // 添加这行，确保它在其他元素之上

        // position: fixed;
        &.scrolled {
            background-color: #ffffff; // 或者你想要的任何颜色

            .van-nav-bar__title,
            .van-icon,
            .van-nav-bar__text {
                color: #333; // 滚动后变为黑色
            }
        }
    }

    .balance_detail_top {
        display: flex;
        justify-content: space-between;
        width: 100%;
        height: 4.72rem;
        background: url('../../images/mine/img_beij4.png') no-repeat center;
        position: relative;
        /* 相对定位 */
        top: -46px;
        /* 根据你的 NavBar 高度调整，Vant UI 默认 NavBar 高度为 46px */
        width: 100%;
        background-size: cover;
        color: #fff;
        text-align: center;
        padding-top: 1.5rem;
        box-sizing: border-box;

        .red_top {
            width: 55%;
            text-align: center;
            position: relative;

            div:nth-child(1) {
                font-family: PingFangSC, PingFang SC;
                font-weight: 500;
                font-size: .6rem;
                color: #FFFFFF;
                line-height: .84rem;
                // text-align: right;
                font-style: normal
            }

            div:nth-child(2) {
                font-family: PingFangSC, PingFang SC;
                font-weight: 400;
                font-size: .32rem;
                color: #FFFFFF;
                line-height: .44rem;
                // text-align: right;
                font-style: normal;
                margin-top: .12rem;
            }
        }

        .red_top::after {
            content: '';
            position: absolute;
            top: .5rem;
            right: 0rem;
            width: .02rem;
            height: .7rem;
            background: rgba(255, 255, 255, 0.5);
            opacity: 0.3;
        }

        img {
            width: 2rem;
            height: 2rem;
            margin-top: -.2rem;
            margin-right: .6rem;
        }

    }

    .balance_detail_content {
        width: 95%;
        height: calc(100vh - 4rem);
        overflow: auto;
        margin: 0 auto;
        border-radius: .2rem;
        // border-top-right-radius: .2rem;
        background: #fff;
        padding-top: .4rem;
        box-sizing: border-box;
        margin-top: -1.9rem;
        position: relative;
        z-index: 1;
        padding: .2rem;
        box-sizing: border-box;

        .balance_detail_content_day {
            min-width: 1.2rem;
            max-width: 2rem;
            border-radius: .36rem;
            font-family: PingFangSC, PingFang SC;
            font-weight: 400;
            font-size: .24rem;
            color: #666666;
            padding: .08rem 0;
            box-sizing: border-box;
            text-align: center;
            font-style: normal;
            border: 1px solid #8A8A8A;

            ::v-deep .van-icon {
                color: #666;
            }
        }

        .balance_list {
            margin-top: .2rem;
            padding-bottom: .2rem;
            border-bottom: 1px solid #E5E5E5;
            display: flex;
            justify-content: space-between;

            .balance_list_left {
                font-family: PingFangSC, PingFang SC;
                font-weight: 400;
                font-size: .28rem;
                color: #333333;
                line-height: .4rem;
                // text-align: left;
                font-style: normal;

                div:last-child {
                    font-family: PingFangSC, PingFang SC;
                    font-weight: 400;
                    font-size: .24rem;
                    color: #999999;
                    line-height: .34rem;
                    // text-align: left;
                    font-style: normal;
                    margin-top: .12rem;

                }
            }

            .balance_list_right {
                font-family: PingFangSC, PingFang SC;
                font-weight: 500;
                font-size: .32rem;
                color: #55A624;
                line-height: .44rem;
                // text-align: center;
                font-style: normal;
            }
        }

    }
}


.red_box2 {
    position: absolute;
    width: 80%;
    // position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 999;
    /* 使子元素绝对定位相对于此容器 */
    // overflow: hidden;
    /* 隐藏溢出的部分 */
    // height: 300px;
    /* 设置容器高度，便于观察效果 */
}

.dynamic-image {
    position: absolute;
    /* 绝对定位 */
    width: 100%;
    /* 图片宽度自适应 */
    transition: transform 1s ease, opacity 1s ease;
    /* 设置过渡效果 */
}

.image1 {
    top: -.8rem;
    /* 第一张图片从顶部开始 */
}

.image2 {
    bottom: 0;
    /* 第二张图片从底部开始 */
}

.fadeOut {
    opacity: 0;
    /* 透明度变为 0 */
}

.image1.fadeOut {
    transform: translateY(200%);
    /* 第一张图片向上移动 */
}

.image2.fadeOut {
    transform: translateY(-100%);
    /* 第二张图片向下移动 */
}

.red_box {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 999;

    .red_box_content {
        width: 5.8rem;
        height: 8.28rem;
        background: url('../../images/mine/red_bg.png') no-repeat center;
        background-size: cover;
        text-align: center;

        .red_title {
            div {
                font-family: PingFangHK, PingFangHK;
                font-weight: 500;
                font-size: .48rem;
                color: #FFDDA8;
                line-height: .66rem;
                text-align: center;
                font-style: normal;
                padding-top: 2.34rem;
            }

            img {
                width: 2.64rem;
                height: 2.64rem;
                padding-top: .92rem;
            }

            .tips {
                font-family: PingFangHK, PingFangHK;
                font-weight: 400;
                font-size: .28rem;
                color: #666666;
                line-height: .4rem;
                text-align: center;
                font-style: normal;
                padding-top: .2rem;

            }
        }

        // div {
        //     font-family: PingFangHK, PingFangHK;
        //     font-weight: 500;
        //     font-size: .48rem;
        //     color: #FFE6A3;
        //     line-height: .66rem;
        //     text-align: center;
        //     font-style: normal;
        //     padding-top: 1.5rem;
        // }



        img {
            width: 1.88rem;
            height: 1.88rem;
            margin-top: 2.52rem;
        }
    }

    img {
        width: .72rem;
        height: .72rem;
        display: block;
        margin: 0 auto;
        margin-top: .3rem;
    }

}
</style>